import moment from 'moment'
import { $post,$get } from '@/api/Api.js'
// import { useStore } from "vuex";
import { computed} from "vue";
// let store = useStore();
// // 获取今天日期
// console.log(moment().format('YYYY-MM-DD'))
// // 获取昨天日期
// console.log(moment().subtract(1, 'days').format('YYYY-MM-DD'))
// // 近一周前
// console.log(moment().subtract('days', 6).format('YYYY-MM-DD'))
// // 获取当月一号
// console.log(moment().startOf('month').format('YYYY-MM-DD'))
// // 当月末尾号
// console.log(moment().endOf('month').format('YYYY-MM-DD'))
// // 上周开始
// console.log(moment().week(moment().week() - 1).startOf('week').format('YYYY-MM-DD'))
// // 上周结束
// console.log(moment().week(moment().week() - 1).endOf('week').format('YYYY-MM-DD'))

// // 上个月开始
// console.log(moment().month(moment().month() - 1).startOf('month').format('YYYY-MM-DD'))
// // 上个月结束
// console.log(moment().month(moment().month() - 1).endOf('month').format('YYYY-MM-DD'))

// 常用方法
const $banseUrl= import.meta.env.VITE_WEB_BASE_URL
//在get请求后面拼接obj参数 import.meta.env.VITE_WEB_BASE_URL
const paramsFun=(obj,flag)=> {
	let result = ''
	let item;
	for (item in obj) {
	  if (obj[item] && String(obj[item])) {
		result += `&${item}=${obj[item]}`
	  }
	}
	console.log(obj)
	if (result&&flag) {
	  result =result.slice(1)
	}
	console.log(result)
	return result
  }
  const $fullUrl=(baseUrl, url)=> {
	let host = baseUrl + "/";
	let url_new = "";
	if (url) {
	  if (url.indexOf("~/") === 0) {
		url_new = url.replace("~/", host);
	  } else if (url.indexOf("/http://") === 0) {
		url_new = url.replace("/http://", "http://");
	  } else if (url.indexOf("/") === 0) {
		url_new = url.replace("/", host);
	  } else if (url.indexOf("/api/"+baseUrl) === 0) {
		url_new =url.replace("/api/"+baseUrl, baseUrl); 
	  } else {
		url_new = url;
	  }
	}
	return url_new;
  }
  //日期处理类库转换YYYY-MM-DD HH:mm:ss 'YYYY-MM-DD'
  const $toTime=(timeStamp,format)=> {
	const stamp = new Date(timeStamp)
	const time = moment(stamp).format(format)
	return time
  }
  //获取地址栏参数地址栏只有一个值的时候
  const $getUrlParams=(urlName)=>{
	let url; //获取url中"?"符后的字串
	if (urlName) {
	  url = urlName;
	} else {
	  url = window.location.hash;
	}

	let paramsObj = new Object();
  	let urlSearchParams = new URLSearchParams(url.split('?')[1]);
	if (url.indexOf("?") != -1) {
	  // let str = url.substr(1);
	//   strs = str.split("&");
	//   for (let i = 0; i < strs.length; i++) {
	// 	paramsObj[str.split("=")[0]] = decodeURI(str.split("=")[1]);
	//   }
		// 获取所有参数的迭代器
		for (const [key, value] of urlSearchParams) {
			paramsObj[key] = value
		}
	}
	console.log(paramsObj)
	return paramsObj;
  }
  const $get_auth=(user_group,fun)=>{
	//查询权限
	
	$get("/api/auth/get_list?"+paramsFun({
		user_group
	},true)).then((json) => {
		window.localStorage.setItem("set_auth",'')
		// 清空权限
		//store.commit("set_auth", []);
		// 判断查询结果
		if(json.result && json.result.list){
			
			let auth= json.result.list;
			 window.localStorage.setItem("set_auth",JSON.stringify(auth))
			// 权限缓存
			//store.commit("set_auth", auth);
			
			// 如果有回调函数则执行回调函数
			if(fun){
				fun();
			}

		}else if(json.error){
			ElMessage.error(json.error.message);
			console.error(json.error);
		}
	})
}
/**
 * 回调函数(中控)
 * @param {String} name 函数名
 * @param {Object} param1
 * @param {Object} param2
 * @param {Object} param3
 * @return {Object} 任意值
 */
const func=(name, param1, param2, param3) =>{
	let f = this[name];
	if (f) {
		if (param1 === undefined) {
			return f();
		} else if (param2 === undefined) {
			return f(param1);
		} else if (param3 === undefined) {
			return f(param1, param2);
		} else {
			return f(param1, param2, param3);
		}
	} else {
		return null;
	}
}
/**
 * 获取权限
 * @param {String} path 路由路径
 */
const $get_power=(path,user_group)=>{
    var list_data = JSON.parse(localStorage.getItem('set_auth'));
  var list = list_data;
	let obj;
	for (let i = 0; i < list.length; i++) {
		let o = list[i];
		if (o.path === path) {
			obj = o;
			break;
		}
	}
	return obj;
}

/**
 * 获取页面标题
 * @param {String} path 路由路径
 */
const $page_title=(path,user_group)=>{
	let o = $get_power(path,user_group);
	if (o) {
		return o.page_title || o.mod_name;
	}
	return "";
}

/**
 * 获取路径对应操作权限 鉴权
 * @param {String} action 操作名
 */
const $check_action=(path, action = "get")=>{
	let o = $get_power(path);
	if (o && o[action]!= 0 && o[action]!= false) {
		return true;
	}
	return false;
}
/**
		 * 敏感词过滤
		 * @param {String} content
		 * @return Array
		 */
const filterSensitiveWords=async(content)=>{
	let json = await $get("/api/sensitive_vocabulary/get_list");
	let wordsList = json.result.list
	let includeWords = []
	console.log(wordsList)
	for (let i = 0; i < wordsList.length; i++) {
		if(content.indexOf(wordsList[i].sensitive_vocabulary) > -1 ){
			includeWords.push(wordsList[i].sensitive_vocabulary)
		}
	}

	return includeWords
}
/**
 * 获取路径对应操作权限 鉴权
 * @param {String} action 操作名
 */
const $check_exam=(path1, action = "get") =>{
	var o = $get_power(path1);
	if (o) {
	  var option = JSON.parse(o.option);
	  if (option[action]) return true;
	}
	return false;
  }
  /**
 * 是否有显示或操作字段的权限
 * @param {String} action 操作名
 * @param {String} field 查询的字段
 */
const $check_field=(action, field, path1)=>{
	var o = $get_power(path1);
	//console.log(o);
	var auth;
	//console.log(o[action]);
	if (o && o[action] != 0 && o[action] != false) {
	  auth = o["field_" + action];
	}
	if (auth) {
	  return auth.indexOf(field) !== -1;
	}
	return false;
  }

/**
 * @description 日期时间转换
 * @param {String} date 时间戳
 */
const formatDate=(newdate) =>{
	let date = new Date(newdate);
	let YY = date.getFullYear() + '-';
	let MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	let DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	let hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	let mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	let ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	return YY + MM + DD +" "+hh + mm + ss;
}

const $check_option=(path,op)  =>{
	var o = $get_power(path);
	if (o){
		var option = JSON.parse(o.option);
		if (option[op])
			return true
	}
	return false;
}
/**
 * 是否有统计字段的权限
 */
const $check_figure=(path) =>{
	var o = $get_power(path);
	if (o){
		var option = JSON.parse(o.option);
		if (option.figure)
			return true
	}
	return false;
}
// get请求拼接参数在url
const $params=(url, data)=> {
	let query = ``
	for (const key in data) {
	  if (data[key] !== null && data[key] !== '') {
		if (query.length === 0) {
		  query += `?${key}=${data[key]}`
		} else {
		  query += `&${key}=${data[key]}`
		}
	  }
	}
	url += query
	return url

}
// 要去除对象中值为空的属性
const removeEmptyProperties=(obj)=> {
	Object.keys(obj).forEach(function(key) {
	  if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
		delete obj[key];
	  }
	});
	return obj;
  }
  /**
 * 用户组是否有这个权限
 * @param {Array} user_group 权限组
 */
  const  $check_group=(user_group,auth)=> {
	var list =auth;
	var bl = false;
	for (var i = 0; i < user_group.length; i++) {
		bl = $check_action(user_group[i]);
		if (bl == true) {
			break;
		}
	}
	return bl;
}
/**
*是否有审核字段的权限
 */
const $check_examine=(path)=>{
	// var path = this.$route.path.replace(/(.*)view/,'$1table');
	// var o = $get_power(path);
	// if (o){
	// 	var option = JSON.parse(o.option);
	// 	if (option.examine)
	// 		return true
	// }
	// return false;
  }
/**
 * 注册时是否有显示或操作字段的权限
 * @param {String} action 操作名
 * @param {String} field 查询的字段
 * @param {String} path 路径
 */
//'add','name','/registered_users/view'
const $check_register_field=(action, field,path)=>{
	var o =$get_power(path);
	console.log(o)
	var auth;
	if (o && o[action] != 0 && o[action] != false) {
		auth = o["field_" + action];
	}
	if (auth) {
		console.log(auth.indexOf(field) !== -1)
		return auth.indexOf(field) !== -1;
	}
	return false;
  }
  
/**
 * @description 删除对象空属性
 * @param {Object} obj 对象
 * @param {Object} includeZero 是否包括0
 * @return {Object} 返回新对象
 */
const $delete=(obj, includeZero)=> {
	var o = Object.assign({}, obj);
	if (includeZero) {
	  for (var k in o) {
		var v = o[k];
		if (!v) {
		  delete o[k];
		}
	  }
	} else {
	  for (var k in o) {
		var v = o[k];
		if (v === '' || v === null || v === undefined) {
		  delete o[k];
		}
	  }
	}
	return o;
  }
  // 获取当前时间戳
  const $get_stamp=()=>{
	return new Date().getTime();
  }

const $get_rand=(len)=>{
	let rand = Math.random();
	return Math.ceil(rand * 10 ** len);
}
/**
 * @description 添加对象属性
 * @param {Object} objA 被添加的对象
 * @param {Object} objB 用作添加的对象
 * @param {Boolean} bl 是否补充没有的对象
 * @return {Object} 新对象
 */
const $push=(objA, objB, bl)=>{
	if (!objA || !objB) {
		return;
	}
	if (bl) {
		for (var k in objB) {
			var value = objB[k];
			if (objA[k] === undefined || objA[k] === null || value === null) {
				objA[k] = value;
			} else {
				var type = typeof(objA[k]);
				var p = typeof(value);
				if (type !== p) {
					if (type === "number") {
						var n = Number(value);
						if (n === NaN) {
							n = 0;
						}
						objA[k] = n;
					} else if (type === "boolean") {
						if (value === '0' || value === 'false' || value === 'False') {
							objA[k] = false;
						} else {
							objA[k] = Boolean(value);
						}
					} else if (type === "string") {
						objA[k] = value.toString();
					} else {
						objA[k] = value;
					}
				} else if (type === "object") {
					if (objA[k].constructor == Array && value.constructor == Array) {
						objA[k].clear();
						objA[k].addList(value);
					} else {
						$push(objA[k], value, bl);
					}
				} else {
					objA[k] = value;
				}
			}
		}
	} else {
		for (var k in objA) {
			var value = objB[k];
			if (objA[k] === null){
				objA[k] = value;
				continue;
			}
			if (value !== undefined && value !== null) {
				var type = typeof(objA[k]);
				var p = typeof(value);
				if (type !== p) {
					if (type === "number") {
						var n = Number(value);
						if (n === NaN) {
							n = 0;
						}
						objA[k] = n;
					} else if (type === "boolean") {
						if (value === '0' || value === 'false' || value === 'False') {
							objA[k] = false;
						} else {
							objA[k] = Boolean(value);
						}
					} else if (type === "string") {
						objA[k] = value.toString();
					} else {
						objA[k] = value;
					}
				} else if (type === "object") {
					if (objA[k].constructor == Array && value.constructor == Array) {
						objA[k].clear();
						objA[k].addList(value);
					} else {
						$push(objA[k], value, bl);
					}
				} else {
					objA[k] = value;
				}
			}
		}
	}
	return objA;
}

/**
 * 验证手机号
 * @param {Object} value 验证值
 */
const $is_phone=(value)=>{
	if (!value || /^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) {
		return '';
	} else {
		return '手机号必须是11位的手机号格式';
	}
}

/**
 * 验证电话
 * @param {Object} value 验证值
 */
const $is_tel=(value)=>{
	if (!value || /^[1][3,4,5,7,8,9][0-9]{9}$/.test(value) || /^\d{3}-\d{7,8}|\d{4}-\d{7,8}|\d{8}$/.test(value)) {
		return '';
	} else {
		return '电话必须是11位或者8位数的电话格式';
	}
}

/**
 * 验证邮箱
 * @param {Object} rule
 * @param {Object} value 验证值
 * @param {Object} callback 返回函数
 */
const $is_email=(value)=>{
	if (!value || /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
		return '';
	} else {
		return '必须是邮箱格式，例：test@test.com';
	}
}
  export {
	// $upload,
	// uploadFile,
	$check_register_field,
	$get_stamp,
  	$get_rand,
	$delete,
	$check_group,
	removeEmptyProperties,
	$params,
	$check_figure,
	$check_option,
	filterSensitiveWords,
	formatDate,
	$get_power,
	$check_exam,
	$check_field,
	$check_action,
	$check_examine,
	$page_title,
	$get_auth,
	func,
	$banseUrl,
	$toTime,
	$fullUrl,
	$getUrlParams,
	paramsFun,
  	$push,
  	$is_phone,
	$is_tel,
	$is_email
  }